# import re
# from django.contrib.auth.backends import ModelBackend
# from jewelry.models import UserInfo
#
#
# class UsernameMobileAuthBackend(ModelBackend):
#     """支持用户名/手机号登录 setting.pt里要设置AUTHENTICATION_BACKENDS"""
#     def authenticate(self, request, username=None, password=None, **kwargs):
#
#         try:
#             # 判断是否是手机号（11位数字）
#             if re.match(r'^1[3-9]\d{9}$', username):
#                 user = UserInfo.objects.get(phone=username)
#             else:
#                 user = UserInfo.objects.get(username=username)
#
#             if user.check_password(password):
#                 return user
#         except UserInfo.DoesNotExist:
#             return None


import re
import logging
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned

# logger = logging.getLogger(__name__)


class UsernameMobileAuthBackend(ModelBackend):
    """支持用户名/手机号登录的强化版认证后端"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        # 空密码直接拒绝
        if not password:
            # logger.warning("空密码尝试登录，用户名/手机号：%s", username)
            return None

        UserModel = get_user_model()  # 获取激活的用户模型

        try:
            # 规范化输入处理
            username = username.strip().lower()  # 去空格并统一小写

            # 判断手机号格式
            if re.match(r'^1[3-9]\d{9}$', username):
                user = self.get_user_by_phone(UserModel, username)
            else:
                user = self.get_user_by_username(UserModel, username)

            # 密码验证核心逻辑
            if user and user.check_password(password):
                # logger.info("用户 %s 登录成功", user.username)
                return user
            else:
                # logger.warning("密码验证失败，用户：%s", username)
                return None

        except (ObjectDoesNotExist, MultipleObjectsReturned) as e:
            # logger.error("用户查询异常：%s，输入值：%s", str(e), username)
            return None
        except Exception as e:
            # logger.critical("认证系统未知错误：%s", str(e), exc_info=True)
            return None

    def get_user_by_username(self, UserModel, username):
        """增强型用户名查询"""
        try:
            # 兼容大小写不敏感的查询
            return UserModel.objects.get(**{UserModel.USERNAME_FIELD + '__iexact': username})
        except ObjectDoesNotExist:
            # logger.debug("用户名不存在：%s", username)
            return None

    def get_user_by_phone(self, UserModel, phone):
        """标准化手机号查询"""
        try:
            # 假设模型有phone字段，且存储规范化的手机号（不带+86前缀）
            return UserModel.objects.get(phone=phone)
        except ObjectDoesNotExist:
            # logger.debug("手机号不存在：%s", phone)
            return None
